#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <stdlib.h>

static void print_ids(const char * info) {
    pthread_t  tid = pthread_self();
    printf("%s tid [0x%04x]\n", info, (unsigned int)tid & 0xffff);
}

static void * thread_function(void * arg) {
    int i = 10;
    pthread_t tid = pthread_self();

    while (--i) {
        printf("thread[0x%04x] count: %d\n", (unsigned int)tid & 0xffff, i);
        sleep(1);
    }

    printf("sub thread exit\n");
    return NULL;
}

int main() {
    pthread_t ntid;
    int ret = pthread_create(&ntid, NULL, thread_function, NULL);
    if (0 != ret) {
        printf("can't create thread: %s\n", strerror(ret));
        exit(-1);
    }

    print_ids("main thread:");

    void * retval;
    /* 
     * int pthread_join(pthread_t thread, void ** retval);
     *  参数
     *  thread  线程标识
     *  retval  线程退出返回值
     * */
    ret = pthread_join(ntid, &retval);
    if (0 != ret) {
        printf("can't join thread(0x%04x): %s\n", (unsigned int)ntid & 0xfffff, 
                strerror(ret));
        exit(-1);
    }
    
    printf("main thread exit\n");
    return 0;
}

